const app = getApp();
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;

/**
 * 初始化数据
 */
function initData(that) {
  inputVal = '';
  var d = wx.getStorageSync('robotHis')
  if(d==""||d==undefined){
    msgList = [{
      speaker: 'server',
      contentType: 'text',
      content: '有什么问题尽管问我哦！'
    },
  ]
  }else{
    msgList = d
  }
  that.setData({
    msgList,
    inputVal
  })
}

/**
 * 计算msg总高度
 */
// function calScrollHeight(that, keyHeight) {
//   var query = wx.createSelectorQuery();
//   query.select('.scrollMsg').boundingClientRect(function(rect) {
//   }).exec();
// }

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: '100vh',
    inputBottom: 0,
    cusHeadIcon:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    initData(this);
    var u = wx.getStorageSync('user')
    if(u!="")
    this.setData({
      cusHeadIcon: u.userxx.avatarUrl,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 获取聚焦
   */
  focus: function (e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      inputBottom: keyHeight + 'px'
    })
    //计算msg高度
    // calScrollHeight(this, keyHeight);

  },

  //失去聚焦(软键盘消失)
  blur: function (e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })

  },

  /**
   * 发送点击监听
   */
  sendClick: function (e) {
console.log(e);
    var v = e.detail.value.trim()
    if (v == undefined || v == "")
      return
    msgList.push({
      speaker: 'customer',
      contentType: 'text',
      content: v
    })
    inputVal = '';
    this.setData({
      msgList,
      inputVal
    });

    wx.request({
      url: 'https://www.daizhongdai.xyz:3007/robot?query='+v+'&id=161199',
      success:res=>{
        var d = res.data.data
        console.log(d);
        if(d.error_code!=0){
          wx.showToast({
            title: '出错了...',
            icon:'error'
          })
          return
        }

        msgList.push({
          speaker: 'server',
          contentType: 'text',
          content: d.result.response.action_list[0].say
        })
        this.setData({
          msgList,
        });
 
      }
    })

  },

  /**
   * 退回上一页
   */
  toBackClick: function () {
    wx.navigateBack({})
  },
  onUnload:function(){
    wx.setStorageSync('robotHis', this.data.msgList)
  }

})